<?php
namespace app\api\controller;

use app\common\model\AccountRecordModel;
use app\common\model\OrderLogModel;
use think\App;
use think\Controller;
use app\common\model\OrderModel;
use app\common\model\CompanyModel;
use app\common\model\AccountModel;
use think\Db;
use Wechat\WxPay;

/**  YSF
 *   回调控制器
 *   Date: 2018/12/17
 * Class Callback
 * @package app\api\controller
 */
class Callback extends Controller
{
    protected $orderModel;
    protected $orderLogModel;
    protected $WxPay;
    protected $wx_config;
    protected $ali_config;
    protected $companyModel;
    protected $accountRecordModel;
    protected $dev_mode;
    protected $api_config;
    protected $accountModel;

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->orderModel = new OrderModel();
        $this->orderLogModel = new OrderLogModel();
        $this->companyModel = new CompanyModel();
        $this->dev_mode = config('api.develop_mode'); // 开发模式
        $this->api_config = config('api_prod.');
        if($this->dev_mode){
            $this->api_config = config('api_dev.');
        }
        $this->wx_config = $this->api_config['wechat'];
        $this->ali_config = $this->api_config['alipay'];
        $this->accountRecordModel = new AccountRecordModel();
        $this->accountModel = new AccountModel();
    }

    /**
     *    微信回调
     */
    public function notifytwo()
    {
        // 接收参数 -- 转换参数
        $postStr = file_get_contents('php://input');
        file_put_contents('./wx_notify.txt', $postStr);
        //$postStr = file_get_contents('./wx_notify.txt');

        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $this->wx_config['payment_type'] = 'NATIVE';

        $this->WxPay = new WxPay($this->wx_config);
        $order_log['operate_time'] = time();
        // 判断支付结果
        if ($postObj->result_code == 'SUCCESS' && $postObj->return_code == 'SUCCESS') {
            $signObj = [];
            foreach ($postObj as $key => $val) {
                if ($key != 'sign') {
                    $signObj[$key] = $val;
                }
            }
            //验证签名
            if ($this->WxPay->getSign($signObj) == $postObj->sign) {
                // 获取订单编号
                $order_sn = $postObj->out_trade_no;
                // 查询订单信息
                $where['order_sn'] = $order_sn;
                $order = $this->orderModel->getOne($where);
                unset($where);
                if (empty($order)) {
                    $return['return_code'] = 'FAIL';
                    $return['return_msg'] = 'error';
                    $return = $this->WxPay->arrayToXml($return);
                    echo $return;
                    exit;
                }

                if ($order['pay_status'] == 2) {
                    $return['return_code'] = 'SUCCESS';
                    $return['return_msg'] = 'OK';
                    $return = $this->WxPay->arrayToXml($return);
                    echo $return;
                    exit;
                }
                // 开启事务
                Db::startTrans();
                try{
                    // 1-- 修改订单支付状态
                    $data['wx_callback_num'] = $postObj->transaction_id;
                    $data['pay_status'] = 2; // 已支付
                    $data['order_status'] = 2; // 已支付
                    $data['pay_time'] = time();
                    $where['order_id'] = $order['order_id'];
                    $this->orderModel->edit($where, $data);
                    unset($where);
                    // 2-- 添加订单日志
                    $order_log['order_id'] = $order['order_id'];
                    $order_log['operation'] = '支付成功';
                    $order_log['remark'] = '微信扫码付';
                    $this->orderLogModel->add($order_log);
                    // 3-- 账户充值
                    if ($order['order_type'] == 2) { // 2表示充值
                        $account_id=$this->changeAccount($order);//修改企业账户信息 新增
                        $this->addAccountRecord($order,$account_id);  // 添加账户充值记录
                    }
                    // 事务提交
                    Db::commit();
                    $res = true;
                } catch (\Exception $e) {
                    $order_log['operation'] = '支付失败回滚';
                    $order_log['operate_time'] = time();
                    $this->orderLogModel->add($order_log);
                    //  事务回滚
                    Db::rollback();
                    $res = false;
                }
                if ($res) {
                    //删除生成的二维码文件
                    try{
                        unlink(__DIR__.'/../../../public/uploads/wxqrcode/'.$order_sn.'.png');
                    } catch (\Exception $e) {

                    }
                    $return['return_code'] = 'SUCCESS';
                    $return['return_msg'] = 'OK';
                    $return = $this->WxPay->arrayToXml($return);
                    echo $return;
                    exit;
                }
            }
        }
        $order_log['operation'] = '支付失败';
        $this->orderLogModel->add($order_log);
        // 错误信息
        $return['return_code'] = 'FAIL';
        $return['return_msg'] = 'error';
        $return = $this->WxPay->arrayToXml($return);
        echo $return;
        exit;
    }

    /**
     *    支付宝回调
     * @throws \Exception
     */
    public function alinotify()
    {
        require_once __DIR__.'/../../../extend/alipay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
        require_once  __DIR__.'/../../../extend/alipay/f2fpay/service/AlipayTradeService.php';


        // 接收参数 -- 转换参数
        $postStr = file_get_contents('php://input');
        file_put_contents('./ali_notify.txt', $postStr);
//        $postStr = file_get_contents('./ali_notify.txt');
//        dump($postStr);die();
        $postStr = urldecode($postStr);
        $postStr = explode('&', $postStr);
        $post = [];
        foreach ($postStr as $k => $v) {
            $str = explode('=', $v);
            $post[$str[0]] = $str[1];
        }

        $alipaySevice = new \AlipayTradeService($this->ali_config);
        $alipaySevice->writeLog(var_export($post, true));
        // 验证签名
        $result = $alipaySevice->check($post);
        if ($result) {
            $order_sn = $post['out_trade_no'];
            $ali_sn = $post['trade_no'];

            // 查询订单信息
            $order = $this->orderModel->getOne(['order_sn' => $order_sn]);
            if (empty($order)) {
                file_put_contents('./ali_notify_test.txt', '失败1');
                echo 'file';
                exit;
            }
            if ($order['pay_status'] == 2) {
                file_put_contents('./ali_notify_test.txt', '成功1');
                echo 'success';
                exit;
            }

            // 开启事务
            Db::startTrans();
            try{
                // 1-- 修改订单状态
                $order_data['order_status'] = 2;
                $order_data['pay_time'] = time();
                $order_data['pay_status'] = 2;
                $order_data['trade_no'] = $ali_sn;
                $where['order_id'] = $order['order_id'];
                $this->orderModel->edit($where, $order_data);
                unset($where);
                // 2-- 写入订单日志
                $order_log['order_id'] = $order['order_id'];
                $order_log['operation'] = '支付成功';
                $order_log['operate_time'] = time();
                $order_log['remark'] = '支付宝当面付';
                $this->orderLogModel->add($order_log);
                // 3-- 账户充值
                if ($order['order_type'] == 2) { // 2表示充值
                    //$this->editCompanyMoney($order);  // 修改企业账户金额 废弃
                    $account_id=$this->changeAccount($order);//修改企业账户信息 新增
                    $this->addAccountRecord($order,$account_id);  // 添加账户充值记录

                }

                // 事务提交
                Db::commit();
                $res = true;
                file_put_contents('./ali_notify_test.txt', '成功2');
            } catch (\Exception $e) {
                // 事务回滚
                Db::rollback();
                $res = false;
                file_put_contents('./ali_notify_test.txt', '失败2'.$e->getMessage());
            }
            if ($res) {
                echo 'success';
                //删除生成的二维码文件
                try{
                    unlink(__DIR__.'/../../../public/uploads/aliqrcode/'.$order_sn.'.png');
                } catch (\Exception $e) {

                }
                exit;
            }

        }
        file_put_contents('./ali_notify_test.txt', '失败1');
        echo 'file';
        exit;
    }

    // 修改企业金额
    private function editCompanyMoney($order=[])
    {
        $where['company_id'] = $order['company_id'];
        $this->companyModel->setInc($where, 'current_money', $order['order_has_pay_money'] + $order['send_money']);
        $this->companyModel->setInc($where, 'cumulative_money', $order['order_has_pay_money'] + $order['send_money']);
        unset($where);
    }

    // 添加账户充值记录
    private function addAccountRecord($order=[],$account_id='')
    {
        //$company_info=$this->accountModel->getCompanyInfo($order['company_id']);

        // 添加账户充值记录
        $data['account_id'] = $account_id; // 账户ID
        $data['order_id'] = $order['order_id']; // 订单ID
        $data['money'] = $order['order_total_money']; // 订单金额
        $data['type'] = 1;  // 1增加
        $data['source'] = 1;  // 1充值
        $data['create_time'] = time();
        $data['remarks'] = '账户充值';
        // 添加
        $this->accountRecordModel->add($data);
        if (!empty($order['send_money'])) {
            // 添加赠送金额记录
            $send_data['account_id'] = $account_id; // 账户ID
            $send_data['order_id'] = $order['order_id']; // 订单ID
            $send_data['money'] = $order['send_money']; // 赠送金额
            $send_data['type'] = 1;  // 1增加
            $send_data['source'] = 2;  // 2赠送
            $send_data['create_time'] = time();
            $send_data['remarks'] = '赠送金额';
            // 添加
            $this->accountRecordModel->add($send_data);
        }
    }
    //新增 变更企业账户信息
    private function changeAccount($order=[]){
       //先查询企业是否有账户信息
        $company_info=$this->companyModel->getOne(['company_id'=>$order['company_id']],'company_id,app_sn,company_no,account');
        $where['id']=$order['account_id'];
        $account_info=$this->accountModel->getOne($where,'id');
        //实际所得金额
        $actual_money=$order['order_has_pay_money'] + $order['send_money'];//支付金额+赠送金额
        if(!empty($account_info)){
            //修改账户信息
            $this->accountModel->setInc($where, 'current_money',$actual_money );
            $this->accountModel->setInc($where, 'total_money', $actual_money);
            $account_id=$account_info['id'];
        }else{
            $add_data=[
                'app_sn'=>$company_info['app_sn'],
                'company_no'=>$company_info['company_no']??'',
                'account_role'=>1,
                'account_sn'=>$company_info['company_no']??'',
                'total_money'=>$actual_money,
                'current_money'=>$actual_money,
                'create_time'=>time(),
            ];
            $account_id=$this->accountModel->add($add_data);
        }
        return $account_id;

    }






}